﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tesseract;
using AForge.Imaging;
using AForge.Imaging.Filters;
using Emgu.CV.Structure;
//using OpenCvSharp;
using static WeChatScreenshotApp.Form1;
//using Emgu.CV;
//using Emgu.CV.Structure;
//using Emgu.CV.CvEnum;
//using Emgu.CV.Reg;
using OpenCvSharp;


namespace WeChatScreenshotApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (var captureForm = new CaptureForm())
            {
                if (captureForm.ShowDialog() == DialogResult.OK)
                {
                    // 创建一个空的 Mat 对象来保存屏幕截图
                    //Mat screenshot = new Mat(new Size(screenWidth, screenHeight), MatType.CV_8UC4);
                    Bitmap screenshot = captureForm.CapturedImage;
                    if (screenshot != null)
                    {
                        // 保存截图到文件
                        string screenshotPath = "screenshot.png";
                        screenshot.Save(screenshotPath, System.Drawing.Imaging.ImageFormat.Png);
                        // 图像预处理
                        //Bitmap processedImage = PreprocessImage(screenshot);                   

                        string processedImagePath = "processed_screenshot.png";
                        //processedImage.Save(processedImagePath, System.Drawing.Imaging.ImageFormat.Png);

                        MemoryStream ms = new MemoryStream();
                        screenshot.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                        byte[] buffer = ms.ToArray();
                        Mat mat = Cv2.ImDecode(buffer, ImreadModes.Color);
                        Mat outputMat = new Mat();
                        outputMat = mat;
                        if (checkBox1.Checked)
                        {
                            Cv2.CvtColor(mat, outputMat, ColorConversionCodes.BGR2GRAY);
                        }
                        if (checkBox2.Checked)
                        {
                            //screenshot = Toqucao(screenshot);
                            Cv2.GaussianBlur(mat, outputMat, new OpenCvSharp.Size(3, 3), 1, 1);
                        }
                        if (checkBox3.Checked)
                        {
                            Cv2.Canny(mat, outputMat, 50, 150);
                        }
                        if (checkBox4.Checked)
                        {
                            //screenshot = Toerzhihua(screenshot);
                            Cv2.Threshold(mat, outputMat, 127, 255, ThresholdTypes.Binary);
                        }
                        mat.SaveImage(processedImagePath);


                        //screenshot.Save(processedImagePath, System.Drawing.Imaging.ImageFormat.Png);
                        // 使用Tesseract进行文字识别
                        using (var engine = new TesseractEngine(@"./tessdata", "chi_sim+eng", EngineMode.Default))
                        {
                            // 设置页面分割模式
                            engine.SetVariable("tessedit_pageseg_mode", "3"); // PSM_SINGLE_LINE
                            using (var img = Pix.LoadFromFile(processedImagePath))
                            {
                                using (var page = engine.Process(img))
                                {
                                    var text = page.GetText();
                                    //MessageBox.Show("Recognized Text:\n" + text);
                                    // 创建子窗体实例并传递参数
                                    using (Form2 form2 = new Form2(text))
                                    {
                                        // 弹出子窗体
                                        if (form2.ShowDialog() == DialogResult.OK)
                                        {
                                            // 处理子窗体返回的结果（如果有）
                                        }
                                    }
                                }
                            }
                        }

                        // 清理
                        File.Delete(screenshotPath);
                    }
                }
            }
        }

        private Bitmap PreprocessImage(Bitmap originalImage)
        {
            // 将图像转换为 24 位 RGB 格式
            //originalImage = ConvertTo24bpp(originalImage);
            //确保图像格式为 24 位 RGB
            //if (originalImage.PixelFormat != PixelFormat.Format24bppRgb)
            //{
            //    originalImage = new Bitmap(originalImage, originalImage.Size);
            //    originalImage = originalImage.Clone(new Rectangle(0, 0, originalImage.Width, originalImage.Height), PixelFormat.Format24bppRgb);
            //}
            // 灰度化
            Bitmap grayImage = new Bitmap(originalImage.Width, originalImage.Height);
            using (Graphics g = Graphics.FromImage(grayImage))
            {
                ColorMatrix colorMatrix = new ColorMatrix(
                    new float[][]
                    {
                        new float[] {0.299f, 0.299f, 0.299f, 0, 0},
                        new float[] {0.587f, 0.587f, 0.587f, 0, 0},
                        new float[] {0.114f, 0.114f, 0.114f, 0, 0},
                        new float[] {0, 0, 0, 1, 0},
                        new float[] {0, 0, 0, 0, 1}
                    });
                ImageAttributes attributes = new ImageAttributes();
                attributes.SetColorMatrix(colorMatrix);
                g.DrawImage(originalImage, new Rectangle(0, 0, originalImage.Width, originalImage.Height), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel, attributes);
            }

            // 去噪：使用中值滤波器去除图像中的噪声
            Median medianFilter = new Median(3);
            Bitmap denoisedImage = medianFilter.Apply(grayImage);

            //denoisedImage = ConvertTo24bpp(denoisedImage);

            // 边缘检测：使用Canny边缘检测增强图像的边缘
            CannyEdgeDetector cannyFilter = new CannyEdgeDetector();
            //Bitmap edgeImage = cannyFilter.Apply(denoisedImage);

            // 二值化
            Bitmap binaryImage = new Bitmap(grayImage.Width, grayImage.Height);
            for (int y = 0; y < grayImage.Height; y++)
            {
                for (int x = 0; x < grayImage.Width; x++)
                {
                    Color color = grayImage.GetPixel(x, y);
                    int threshold = 128;
                    int gray = color.R;
                    binaryImage.SetPixel(x, y, gray > threshold ? Color.White : Color.Black);
                }
            }

            return binaryImage;
        }
        private Bitmap ConvertTo24bpp(Bitmap image)
        {
            if (image.PixelFormat == PixelFormat.Format24bppRgb)
            {
                return image;
            }

            Bitmap newImage = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
            using (Graphics g = Graphics.FromImage(newImage))
            {
                g.DrawImage(image, 0, 0, image.Width, image.Height);
            }
            return newImage;
        }

        private Bitmap PreprocessImage2(Bitmap originalImage)
        {
            // 灰度化
            Bitmap grayImage = new Bitmap(originalImage.Width, originalImage.Height);
            using (Graphics g = Graphics.FromImage(grayImage))
            {
                ColorMatrix colorMatrix = new ColorMatrix(
                    new float[][]
                    {
                        new float[] {0.299f, 0.299f, 0.299f, 0, 0},
                        new float[] {0.587f, 0.587f, 0.587f, 0, 0},
                        new float[] {0.114f, 0.114f, 0.114f, 0, 0},
                        new float[] {0, 0, 0, 1, 0},
                        new float[] {0, 0, 0, 0, 1}
                    });
                ImageAttributes attributes = new ImageAttributes();
                attributes.SetColorMatrix(colorMatrix);
                g.DrawImage(originalImage, new Rectangle(0, 0, originalImage.Width, originalImage.Height), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel, attributes);
            }

            // 去噪：使用中值滤波器去除图像中的噪声
            Median medianFilter = new Median(3);
            Bitmap denoisedImage = medianFilter.Apply(grayImage);

            // 边缘检测：使用Canny边缘检测增强图像的边缘
            //CannyEdgeDetector cannyFilter = new CannyEdgeDetector();
            //Bitmap edgeImage = cannyFilter.Apply(denoisedImage);
            Bitmap edgeImage = denoisedImage;
            // 二值化
            Bitmap binaryImage = new Bitmap(edgeImage.Width, edgeImage.Height);
            for (int y = 0; y < edgeImage.Height; y++)
            {
                for (int x = 0; x < edgeImage.Width; x++)
                {
                    Color color = edgeImage.GetPixel(x, y);
                    int threshold = 128;
                    int gray = color.R;
                    binaryImage.SetPixel(x, y, gray > threshold ? Color.White : Color.Black);
                }
            }

            //// 倾斜校正：使用HoughLineTransformation进行倾斜校正
            //HoughLineTransformation houghLine = new HoughLineTransformation();
            //houghLine.ProcessImage(binaryImage);
            //LineSegment2D line = houghLine.GetLinesByRelativeIntensity(0.5f)[0];
            //double angle = -Math.Atan2(line.Y2 - line.Y1, line.X2 - line.X1) * 180.0 / Math.PI;

            // 旋转图像
            //RotateBilinear rotateFilter = new RotateBilinear(angle);
            //Bitmap rotatedImage = rotateFilter.Apply(binaryImage);

            return binaryImage;
        }



        private Mat Tohuiduxxx(Bitmap originalImage)
        {
            //Bitmap bitmap = new Bitmap("your_image_path.jpg");
            MemoryStream ms = new MemoryStream();
            originalImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            byte[] buffer = ms.ToArray();
            Mat mat = Cv2.ImDecode(buffer, ImreadModes.Color);
            Mat grayMat = new Mat();
            Cv2.CvtColor(mat, grayMat, ColorConversionCodes.BGR2GRAY);
            // 或者使用 CvInvoke 从 Bitmap 转换为 Mat
            // Mat mat = CvInvoke.Imread(bitmap, ImreadModes.AnyColor);
            return grayMat;
        }

        private Mat Toquzaoying(Bitmap originalImage)
        {
            MemoryStream ms = new MemoryStream();
            originalImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            byte[] buffer = ms.ToArray();
            Mat mat = Cv2.ImDecode(buffer, ImreadModes.Color);
            Mat denoisedImage = new Mat();
            Cv2.GaussianBlur(mat, denoisedImage, new OpenCvSharp.Size(3, 3), 1, 1);
            return denoisedImage;
        }


        /// <summary>
        /// 灰度
        /// </summary>
        /// <param name="originalImage"></param>
        /// <returns></returns>
        private Bitmap Tohuidu(Bitmap originalImage)
        {
            


            Bitmap grayImage = new Bitmap(originalImage.Width, originalImage.Height);
            using (Graphics g = Graphics.FromImage(grayImage))
            {
                ColorMatrix colorMatrix = new ColorMatrix(
                    new float[][]
                    {
                        new float[] {0.299f, 0.299f, 0.299f, 0, 0},
                        new float[] {0.587f, 0.587f, 0.587f, 0, 0},
                        new float[] {0.114f, 0.114f, 0.114f, 0, 0},
                        new float[] {0, 0, 0, 1, 0},
                        new float[] {0, 0, 0, 0, 1}
                    });
                ImageAttributes attributes = new ImageAttributes();
                attributes.SetColorMatrix(colorMatrix);
                g.DrawImage(originalImage, new Rectangle(0, 0, originalImage.Width, originalImage.Height), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel, attributes);
            }
            return grayImage;
        }

        /// <summary>
        /// 降噪
        /// </summary>
        /// <param name="originalImage"></param>
        /// <returns></returns>
        private Bitmap Toqucao(Bitmap originalImage)
        {

            // 去噪：使用中值滤波器去除图像中的噪声
            Median medianFilter = new Median(3);
            Bitmap denoisedImage = medianFilter.Apply(originalImage);
            return denoisedImage;
        }

        /// <summary>
        /// 二值化
        /// </summary>
        /// <param name="originalImage"></param>
        /// <returns></returns>
        private Bitmap Toerzhihua(Bitmap originalImage)
        {
            // 二值化
            Bitmap binaryImage = new Bitmap(originalImage.Width, originalImage.Height);
            for (int y = 0; y < originalImage.Height; y++)
            {
                for (int x = 0; x < originalImage.Width; x++)
                {
                    Color color = originalImage.GetPixel(x, y);
                    int threshold = 128;
                    int gray = color.R;
                    binaryImage.SetPixel(x, y, gray > threshold ? Color.White : Color.Black);
                }
            }
            return binaryImage;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
    public class CaptureForm : Form
    {
        private Rectangle _selectionRect;
        private System.Drawing.Point _startPoint;
        private bool _isSelecting;
        private Bitmap _screenBitmap;

        public CaptureForm()
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            this.DoubleBuffered = true;
            this.Cursor = Cursors.Cross;

            _screenBitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            using (Graphics g = Graphics.FromImage(_screenBitmap))
            {
                g.CopyFromScreen(System.Drawing.Point.Empty, System.Drawing.Point.Empty, _screenBitmap.Size);
            }
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            _startPoint = e.Location;
            _isSelecting = true;
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (_isSelecting)
            {
                _selectionRect = new Rectangle(
                    Math.Min(_startPoint.X, e.X),
                    Math.Min(_startPoint.Y, e.Y),
                    Math.Abs(_startPoint.X - e.X),
                    Math.Abs(_startPoint.Y - e.Y)
                );
                this.Invalidate();
            }
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            _isSelecting = false;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.DrawImage(_screenBitmap, System.Drawing.Point.Empty);
            if (_isSelecting)
            {
                using (Pen pen = new Pen(Color.Red, 2))
                {
                    e.Graphics.DrawRectangle(pen, _selectionRect);
                }
            }
        }

        public Bitmap CapturedImage
        {
            get
            {
                if (_selectionRect.Width > 0 && _selectionRect.Height > 0)
                {
                    return _screenBitmap.Clone(_selectionRect, _screenBitmap.PixelFormat);
                }
                return null;
            }
        }
    }
}
